﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace TankGame
{
    public class ParticleEngine4
    {
        private Random random;
        public Vector2 EmitterLocation { get; set; }
        public float angle { get; set; }
        private List<Particle> particles;
        private List<Texture2D> textures;
        public Boolean generate = true;

        public ParticleEngine4(List<Texture2D> textures, Vector2 location)
        {
            EmitterLocation = location;
            this.textures = textures;
            this.particles = new List<Particle>();
            random = new Random();
        }

        public void Update()
        {
            for (int particle = 0; particle < particles.Count; particle++)
            {
                particles[particle].Update();
                if (particles[particle].TTL <= 0)
                {
                    particles.RemoveAt(particle);
                    particle--;
                }
            }
        }

        public void createFlames()
        {
            int total = 10;
            for (int i = 0; i <= total; i++)
            {
                particles.Add(GenerateNewFireParticle());
            }
        }

        private Particle GenerateNewFireParticle()
        {
            Texture2D texture = textures[random.Next(textures.Count)];
            Vector2 position = EmitterLocation;
            double spread = (random.NextDouble() * 0.2) - 0.4;
            const float spreadCoeff = 0.25f;
            float ang = this.angle + (float)spread*((this.angle * (float)spread) * spreadCoeff)*((float)random.NextDouble()*3-(float)1.5);
            float speed = (float)random.NextDouble() * 6;
            float num1 = (float)Math.Cos(ang) * speed;
            float num2 = (float)Math.Sin(ang) * speed;
            Vector2 velocity = new Vector2(num1, num2);
            int randomg = random.Next(80, 140);
            Color color = new Color(255, randomg, 0, 20);
            float angle = MathHelper.ToRadians(0f);
            float angularVelocity = 0.1f * (float)(random.NextDouble() * 2 - 1);
            float size = 0.87f - (float)(random.NextDouble() * 0.2);
            int ttl = 25 + random.Next(180);

            return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl);
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            for (int index = 0; index < particles.Count; index++)
            {
                particles[index].Draw(spriteBatch);
            }
        }
    }
}
